package org.alis.smallcc.alis.tools.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class AlisLock implements Lock {

    private Sync sync = new Sync();

    @Override
    public void lock() {
        sync.acquire(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

    @Override
    public boolean tryLock() {
        try {
            return sync.tryAcquireNanos(1, 1000);
        } catch (InterruptedException e) {
            log.error("线程异常中断，异常堆栈——>", e);
            Thread.currentThread().interrupt();
        }
        return false;
    }

    @Override
    public boolean tryLock(long time, @Nullable TimeUnit unit) throws InterruptedException {
        return sync.tryAcquireNanos(1, TimeUnit.NANOSECONDS.convert(time, unit));

    }

    @Override
    public void unlock() {
        sync.release(1);
    }

    @Override
    @Nonnull
    public Condition newCondition() {
        return sync.new ConditionObject();
    }

    public boolean isLock() {
        return sync.isLock();
    }

    /**
     * 同步器
     */
    private class Sync extends AbstractQueuedSynchronizer {
        /**
		 * 
		 */
		private static final long serialVersionUID = -1723245154445052965L;
		private AtomicInteger state = new AtomicInteger(0);

        @Override
        protected boolean tryAcquire(int arg) {
            return state.compareAndSet(0, arg);
        }

        @Override
        protected boolean tryRelease(int arg) {
            return state.compareAndSet(state.get(), arg);
        }
        @Override
        protected  boolean isHeldExclusively(){
            return isLock();
        }

        boolean isLock() {
            return state.get() != 0;
        }

    }
}
